package leetcode.top100;

import offerbook.Code60_LevelPrintTree;
import offerbook.Code61_LevelZigZagPrintTree;
import utils.TreeNode;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 给你一个二叉树，请你返回其按 层序遍历 得到的节点值。 （即逐层地，从左到右访问所有节点）。
 *
 *  
 *
 * 示例：
 * 二叉树：[3,9,20,null,null,15,7],
 *
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * 返回其层次遍历结果：
 *
 * [
 *   [3],
 *   [9,20],
 *   [15,7]
 * ]
 *{@link Code60_LevelPrintTree}
 *{@link Code61_LevelZigZagPrintTree}
 * @date 2020/4/7 17:03
 */
public class Code102_LevelPrintBT {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new LinkedList<>();
        if(root == null) return res;
        List<Integer> level = new LinkedList<>();
        int toBePrint = 1;
        int nextPrint = 0 ;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            if(toBePrint == 0){
                toBePrint = nextPrint;
                nextPrint = 0;
                res.add(new LinkedList<>(level));
                level.clear();
            }
            root = queue.poll();
            level.add(root.val);
            toBePrint--;
            //当前层次遍历完毕.写在这有BUG，比如第一进来执行，满足，
            // 但是nextPrint为0.
          /*  if(--toBePrint == 0){
                toBePrint = nextPrint;
                nextPrint = 0;
                res.add(new LinkedList<>(level));
                level.clear();
            }*/
            //统计左右孩子
            if(root.left!= null){
                nextPrint++;
                queue.offer(root.left);
            }
            if(root.right != null){
                nextPrint++;
                queue.offer(root.right);
            }
        }
        //最后一层
        res.add(new LinkedList<>(level));
        return res;
    }

    public static void main(String[] args) {
        TreeNode node = new TreeNode(3);
        node.left = new TreeNode(9);
        node.right = new TreeNode(20);
        node.right.left = new TreeNode(15);
        node.right.right = new TreeNode(7);
        new Code102_LevelPrintBT().levelOrder(node).forEach(System.out::println);
    }
}
